package cn.iocoder.boot.springai001.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.content.Media;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

public class MediaUtils {

    private static final Logger log = LoggerFactory.getLogger(MediaUtils.class);

    public static Media[] mediaArray(List<String> imageUrls) {
        List<Media> medias = new ArrayList<>();
        if (CollectionUtils.isEmpty(imageUrls)) {
            return null;
        }
        for (String imageUrl : imageUrls) {
            if (StrUtil.isBlank(imageUrl)) {
                continue;
            }
            if (!HttpUtil.isHttp(imageUrl) && !HttpUtil.isHttps(imageUrl)) {
                continue;
            }
            Media media = media(imageUrl);
            if (media == null) {
                continue;
            }
            medias.add(media);
        }
        return medias.toArray(new Media[0]);
    }

    public static Media media(String imageUrl) {
        try {
            return Media.builder()
                    .mimeType(getMimeType(imageUrl))
                    .data(URI.create(imageUrl))
                    .build();
        } catch (Exception e) {
            log.error("图片地址错误", e);
        }
        return null;
    }

    public static MimeType getMimeType(String url) {
        return MimeTypeUtils.parseMimeType(FileUtil.getMimeType(url));
    }

}
